﻿using PayrollHR.Web;
using Payroll.BusinessLogic.Devices;
using Payroll.BusinessLogic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Payroll.BusinessLogic.Configuration;
using Payroll.Controls;
using System.Data;
using Payroll.Common.Utils;

namespace PayrollHR.Administration.Modules
{
    public partial class OrderAddControl : BasePayrollAdministrationUserControl
    {
        private string[] m_field = { "CustomerID", "CustName", "CustTaxCode", "CustMobile" };
        private string m_fieldName = "";
        public int OrderId
        {
            get
            {
                return CommonHelper.QueryStringInt("OrderId");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = this.GetOrderDevice();
            if (!IsPostBack)
            {
                //this.CreateColumn(dt);
            }
            this.CreateColumn(dt);
            this.Bind(dt);
        }
        private void CreateColumn(DataTable dt)
        {
            foreach (DataColumn info in dt.Columns)
            {
                var item = (from f in m_field
                            where f.ToLower() == info.ColumnName.ToLower()
                            select f).FirstOrDefault();
                if (CommonHelper.IsNull(item))
                {
                    TemplateField tfield = new TemplateField();
                    tfield.HeaderText = info.ColumnName;
                    //bfield.DataField = "Name"
                    tfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, info.ColumnName);
                    tfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, info.ColumnName);

                    var gridBoundColumns = gvOrder.Columns.OfType<TemplateField>();
                    if (gridBoundColumns.Any(bf => bf.HeaderText.Equals(info.ColumnName)) == false)//if (gridBoundColumns.Any(bf => bf.HeaderText.Equals(info.ColumnName)) == false)
                    {
                        gvOrder.Columns.Add(tfield);
                    }
                    else {

                        gvOrder.Columns.Remove(gridBoundColumns.FirstOrDefault());
                        gvOrder.Columns.Add(tfield);
                    }
                }
            } //OnRowDataBound="gvOrder_RowDataBound"
        }
        private DataTable GetOrderDevice()
        {
            var order = this.OrderService.GetById(this.OrderId);
            if (!CommonHelper.IsNull(order))
            {
                dpTransdate.SelectedDate = order.Transdate;
                txtNote.Text = order.Note;
            }
            int? orderId = null;
            if (this.OrderId > 0)
                orderId = this.OrderId;
            DataTable dt = new DataTable();
            SqlHelper.OrderDeviceGetDynamicContents(orderId, ref dt);
            return dt;
        }
        private void Bind(DataTable dt)
        {
            gvOrder.DataSource = dt;
            gvOrder.DataBind();
        }
        private void BindGrid()
        {
            DataTable dt = this.GetOrderDevice();
            this.CreateColumn(dt);
            this.Bind(dt);
        }
        private void DevicesFillDropDowns()
        {
            //ddlDevices.Items.Clear();
            //var deviceColection = this.DeviceService.GetAllDevice(null, null);
            //deviceColection.Insert(0, new Devices { DeviceID = 0, DeviceName = "----None----" });
            //foreach (var device in deviceColection)
            //{
            //    ListItem item2 = new ListItem(device.DeviceName, device.DeviceID.ToString());
            //    this.ddlDevices.Items.Add(item2);
            //}
        }
        private List<OrderDevice> GetOrder(ref List<OrderDevice> List)
        {
            var device = this.DeviceService.GetAllDevice(null, null);
            int N = gvOrder.Columns.Count;
            TextBox txtQuantity = null;
            int CustomerID = 0;
            int order_id = this.OrderId;
            try
            {
                foreach (GridViewRow row in gvOrder.Rows)
                {
                    CustomerID = CommonHelper.ToInteger(gvOrder.DataKeys[row.RowIndex].Value);
                    for (int Index = 3; Index < N; Index++)
                    {
                        string columnName = gvOrder.Columns[Index].HeaderText;
                        //txtQuantity = row.FindControl("txtQuantity" + Index.ToString()) as TextBox;
                        txtQuantity = row.FindControl("txtQuantity" + columnName) as TextBox;// row.Cells[Index].FindControl("txtQuantity") as TextBox;                        
                        int DeviceId = (device.Where(d => d.DeviceCode == columnName)).FirstOrDefault().DeviceID.Value;
                        List.Add(new OrderDevice { OrderID = order_id, CustomerID = CustomerID, Quantity = CommonHelper.ToInteger(txtQuantity.Text), DeviceID = DeviceId });
                    }
                }
            }
            catch (Exception ex)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('error: " + ex.Message + "')", true);
                ProcessException(ex);
            }
            return List;
        }
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                List<OrderDevice> List = new List<OrderDevice>();
                this.GetOrder(ref List);
                Order order = new Order { OrderID = this.OrderId, Transdate = dpTransdate.SelectedDate.Value, Note = txtNote.Text.Trim(), OrderDevice = List };
                int id = this.OrderService.Save(order);
                if (Page.IsValid)
                    Response.Redirect("DevicesManager.aspx");
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
            finally
            {
                SaveButton.Enabled = true;
                SaveAndStayButton.Enabled = true;
            }

        }

        protected void SaveAndStayButton_Click(object sender, EventArgs e)
        {
            try
            {
                int order_id = this.OrderId;
                List<OrderDevice> List = new List<OrderDevice>();
                this.GetOrder(ref List);
                Order order = new Order
                {
                    OrderID = this.OrderId,
                    Transdate = dpTransdate.SelectedDate.Value,
                    Note = txtNote.Text.Trim(),
                    OrderDevice = List,
                    Createby = PayrollContext.Current.Session.EmployeeId,
                    Modified = PayrollContext.Current.Session.EmployeeId,
                    CreateDate = DateTime.Now,
                    ModifiedDate = DateTime.Now
                };
                int orderid = this.OrderService.Save(order);
                if (Page.IsValid)
                    Response.Redirect(string.Format("OrderAdd.aspx?OrderId={0}", orderid));
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
            finally
            {
                SaveButton.Enabled = true;
                SaveAndStayButton.Enabled = true;
            }
        }

        protected void gvOrder_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvOrder.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }

        protected void gvOrder_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int N = gvOrder.Columns.Count;
                for (int index = 3; index < N; index++)
                {
                    m_fieldName = gvOrder.Columns[index].HeaderText;
                    TextBox txtQuantity = new TextBox();
                    txtQuantity.ID = "txtQuantity" + index.ToString();
                    txtQuantity.Attributes.Add("runat", "server");
                    txtQuantity.Style["text-align"] = "center";
                    txtQuantity.DataBinding += new EventHandler(txtQuantity_DataBinding);
                    e.Row.Cells[index].Controls.Add(txtQuantity);
                }
            }
        }

        void txtQuantity_DataBinding(object sender, EventArgs e)
        {
            TextBox txtdata = (TextBox)sender;
            GridViewRow container = (GridViewRow)txtdata.NamingContainer;
            object dataValue = DataBinder.Eval(container.DataItem, m_fieldName);
            if (dataValue != DBNull.Value)
            {
                txtdata.Text = dataValue.ToString();
            }
            else
            {
                txtdata.Text = "";
            }
        }
    }
}